<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="1.什么是MyBatis? MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code，并且改名为MyBatis 。2013年11月迁移到Github。 iBATIS一词来源于“internet”和“abatis”的组合，是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQ">
<meta property="og:type" content="article">
<meta property="og:title" content="MyBatis学习笔记-01">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/10/2016-06-10-mybatis-study%20notes01/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="1.什么是MyBatis? MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code，并且改名为MyBatis 。2013年11月迁移到Github。 iBATIS一词来源于“internet”和“abatis”的组合，是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQ">
<meta property="og:locale">
<meta property="og:image" content="http://ww3.sinaimg.cn/mw690/63503acbjw1f4pf96s0tcj209302caa2.jpg">
<meta property="og:image" content="http://i4.buimg.com/47c91060a0871659.png">
<meta property="og:image" content="http://i4.buimg.com/60494497248097cf.png">
<meta property="og:image" content="http://i4.buimg.com/fb28faf508066198.png">
<meta property="og:image" content="http://i4.buimg.com/0382b4a78a6080a2.png">
<meta property="og:image" content="http://i4.buimg.com/134368652f63916c.png">
<meta property="article:published_time" content="2016-06-09T16:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="MyBatis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ww3.sinaimg.cn/mw690/63503acbjw1f4pf96s0tcj209302caa2.jpg">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/10/2016-06-10-mybatis-study%20notes01/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>MyBatis学习笔记-01 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AFMyBatis"><span class="nav-number">1.</span> <span class="nav-text">1.什么是MyBatis?</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-MyBatis%E6%A1%86%E6%9E%B6%E5%8E%9F%E7%90%86"><span class="nav-number">2.</span> <span class="nav-text">2.MyBatis框架原理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#MyBatis%E7%9A%84%E5%8A%9F%E8%83%BD%E6%9E%B6%E6%9E%84%E5%88%86%E4%B8%BA%E4%B8%89%E5%B1%82"><span class="nav-number">2.1.</span> <span class="nav-text">MyBatis的功能架构分为三层</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#MyBatis%E6%A1%86%E6%9E%B6%E6%9E%B6%E6%9E%84%E6%B5%81%E7%A8%8B"><span class="nav-number">2.2.</span> <span class="nav-text">MyBatis框架架构流程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-MyBatis%E7%9A%84%E4%BC%98%E7%82%B9%E4%B8%8E%E7%BC%BA%E7%82%B9"><span class="nav-number">3.</span> <span class="nav-text">3.MyBatis的优点与缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-MyBatis%E5%85%A5%E9%97%A8"><span class="nav-number">4.</span> <span class="nav-text">4.MyBatis入门</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-%E8%87%AA%E5%A2%9E%E4%B8%BB%E9%94%AE"><span class="nav-number">5.</span> <span class="nav-text">5.自增主键</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%8E-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">5.1.</span> <span class="nav-text">#{} 与 ${}的区别</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-%E4%BD%BF%E7%94%A8Mapper%E6%9E%84%E5%BB%BADao"><span class="nav-number">6.</span> <span class="nav-text">6.使用Mapper构建Dao</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%A7%84%E8%8C%83"><span class="nav-number">6.1.</span> <span class="nav-text">规范</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/10/2016-06-10-mybatis-study%20notes01/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MyBatis学习笔记-01
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2016-06-10 00:00:00" itemprop="dateCreated datePublished" datetime="2016-06-10T00:00:00+08:00">2016-06-10</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">后端</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/Java/MyBatis/" itemprop="url" rel="index"><span itemprop="name">MyBatis</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p><img src="http://ww3.sinaimg.cn/mw690/63503acbjw1f4pf96s0tcj209302caa2.jpg" alt="MyBatis"></p>
<h3 id="1-什么是MyBatis"><a href="#1-什么是MyBatis" class="headerlink" title="1.什么是MyBatis?"></a>1.什么是MyBatis?</h3><ul>
<li>MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code，并且改名为MyBatis 。2013年11月迁移到Github。</li>
<li>iBATIS一词来源于“internet”和“abatis”的组合，是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects（DAO）</li>
<li>MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。</li>
<li>MyBatis 可以对配置和原生Map使用简单的 XML 或注解，将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。</li>
</ul>
<h3 id="2-MyBatis框架原理"><a href="#2-MyBatis框架原理" class="headerlink" title="2.MyBatis框架原理"></a>2.MyBatis框架原理</h3><h4 id="MyBatis的功能架构分为三层"><a href="#MyBatis的功能架构分为三层" class="headerlink" title="MyBatis的功能架构分为三层"></a>MyBatis的功能架构分为三层</h4><ol>
<li>API接口层：提供给外部使用的接口API，开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。  </li>
<li>数据处理层：负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。  </li>
<li>基础支撑层：负责最基础的功能支撑，包括连接管理、事务管理、配置加载和缓存处理，这些都是共用的东西，将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。<br><img src="http://i4.buimg.com/47c91060a0871659.png"></li>
</ol>
<h4 id="MyBatis框架架构流程"><a href="#MyBatis框架架构流程" class="headerlink" title="MyBatis框架架构流程"></a>MyBatis框架架构流程</h4><p><img src="http://i4.buimg.com/60494497248097cf.png"></p>
<ol>
<li>MyBatis应用程序通过读取XML配置文件,构造出SqlSessionFactory(SQL会话工厂)。</li>
<li>SqlSessionFactory再根据配置,构造一个SqlSession(SQL会话)。MyBatis通过SqlSession完成数据库操作。</li>
<li>SqlSession本身不能直接操作数据库,它是通过底层Executor接口操作数据库的。Executor有2个实现类,默认使用缓存执行器。</li>
<li>Executor将处理的SQL信息封装到一个底层对象 MappedStatement 中。该对象包含了SQL语句、输入参数信息、输出结果集信息。</li>
<li>输入参数和输出结果集的映射类型为java的简单类型、HashMap集合类型、POJO对象类型。</li>
</ol>
<h3 id="3-MyBatis的优点与缺点"><a href="#3-MyBatis的优点与缺点" class="headerlink" title="3.MyBatis的优点与缺点"></a>3.MyBatis的优点与缺点</h3><p>优点</p>
<ul>
<li>学习成本低、简单易学。</li>
<li>灵活性较高,可以直接对SQL进行性能优化。</li>
<li>SQL与业务逻辑代码低耦合,提高了维护性。</li>
<li>可以编写动态SQL语句。</li>
</ul>
<p>缺点</p>
<ul>
<li>SQL语句依赖数据库,即数据库发生变更时,需要重新写SQL语句, 移植性较差。</li>
<li>SQL语句繁多,工作量大。</li>
<li>二级缓存机制不佳。</li>
</ul>
<h3 id="4-MyBatis入门"><a href="#4-MyBatis入门" class="headerlink" title="4.MyBatis入门"></a>4.MyBatis入门</h3><p>我们使用MyBatis完成一个根据id查询用户的需求。</p>
<p><strong>创建一个JavaBean</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public class User &#123;</span><br><span class="line"></span><br><span class="line">     private int id ;</span><br><span class="line">     private String username ;&#x2F;&#x2F; 姓名</span><br><span class="line">     private String sex ;&#x2F;&#x2F; 性别</span><br><span class="line">     private Date birthday ;&#x2F;&#x2F; 生日</span><br><span class="line">     private String address ;&#x2F;&#x2F; 地址</span><br></pre></td></tr></table></figure>
<p><strong>为User类配置一个映射文件</strong></p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;? xml version =<span class="string">&quot;1.0&quot;</span> encoding= <span class="string">&quot;UTF-8&quot;</span> ?&gt;</span><br><span class="line">&lt;! DOCTYPE mapper</span><br><span class="line">PUBLIC <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span><br><span class="line"><span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span> &gt;</span><br><span class="line">&lt; mapper namespace =<span class="string">&quot;com.sun.test.mapper.UserMapper&quot;</span> &gt;</span><br><span class="line">     &lt;!-- 根据id查询User</span><br><span class="line">          在命名空间 com.sun.test.mapper.UserMapper中定义了一个id为findById的映射语句。</span><br><span class="line">          当我们调用时可以使用 namespace.id 来进行调用。</span><br><span class="line">          即：com.sun.test.mapper.UserMapper.findById </span><br><span class="line">     --&gt;</span><br><span class="line">     &lt;select id= <span class="string">&quot;findById&quot;</span> parameterType =<span class="string">&quot;int&quot;</span> resultType =<span class="string">&quot;com.sun.test.entity.User&quot;</span> &gt;</span><br><span class="line">         select * from user where id = #&#123;id&#125;</span><br><span class="line">     &lt;/select &gt;</span><br><span class="line">&lt;/ mapper&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li>命名空间(Namespace): 必须且非常重要,最好使用对应mapper接口的全限定名(比如:com.sun.test.mapper.UserMapper )。</li>
<li>parameterType: 输入参数的类型,可以使用类型的全限定名或者别名。</li>
<li>resultType: 返回参数的类型,如果是集合类型,则应使用集合内可以包含的类型,而不能是集合本身,可以使用类型的全限定名或者别名。</li>
</ul>
<p><strong>创建一个全局配置文件,并配置数据源、事务管理器、映射文件等基本配置。</strong>    </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;? xml version &#x3D;&quot;1.0&quot; encoding&#x3D; &quot;UTF-8&quot; ?&gt;</span><br><span class="line">&lt;! DOCTYPE configuration</span><br><span class="line">  PUBLIC &quot;-&#x2F;&#x2F;mybatis.org&#x2F;&#x2F;DTD Config 3.0&#x2F;&#x2F;EN&quot;</span><br><span class="line">  &quot;http:&#x2F;&#x2F;mybatis.org&#x2F;dtd&#x2F;mybatis-3-config.dtd&quot; &gt;</span><br><span class="line">&lt; configuration&gt;</span><br><span class="line">     &lt;environments default&#x3D; &quot;development&quot;&gt;</span><br><span class="line">          &lt; environment id&#x3D; &quot;development&quot; &gt;</span><br><span class="line">              &lt;!-- 配置事务管理器 --&gt;</span><br><span class="line">              &lt; transactionManager type &#x3D;&quot;JDBC&quot; &#x2F;&gt;</span><br><span class="line">              &lt;!-- 配置数据源 --&gt;</span><br><span class="line">              &lt; dataSource type &#x3D;&quot;POOLED&quot; &gt;</span><br><span class="line">                  &lt; property name &#x3D;&quot;driver&quot; value &#x3D;&quot;com.mysql.jdbc.Driver&quot; &#x2F;&gt;</span><br><span class="line">                  &lt; property name &#x3D;&quot;url&quot; value &#x3D;&quot;jdbc:mysql:&#x2F;&#x2F;&#x2F;mybatis&quot; &#x2F;&gt;</span><br><span class="line">                  &lt; property name &#x3D;&quot;username&quot; value &#x3D;&quot;root&quot; &#x2F;&gt;</span><br><span class="line">                  &lt; property name &#x3D;&quot;password&quot; value &#x3D;&quot;root&quot; &#x2F;&gt;</span><br><span class="line">              &lt;&#x2F; dataSource&gt;</span><br><span class="line">          &lt;&#x2F; environment&gt;</span><br><span class="line">     &lt;&#x2F;environments &gt;</span><br><span class="line">     &lt;!-- 配置映射文件 --&gt;</span><br><span class="line">     &lt;mappers &gt;</span><br><span class="line">          &lt;!-- 使用package可以查找到所有 mapper接口与 mapper映射文件但需要同名并且放在同一包下 --&gt;</span><br><span class="line">          &lt; package name &#x3D;&quot;com.sun.test.mapper&quot; &#x2F;&gt;</span><br><span class="line">     &lt;&#x2F;mappers &gt;</span><br><span class="line">&lt;&#x2F; configuration&gt;</span><br></pre></td></tr></table></figure>
<p><strong>测试</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">         <span class="comment">// 获得配置文件的资源流</span></span><br><span class="line">        InputStream inputStream = Resources.getResourceAsStream( <span class="string">&quot;sqlMapConfig.xml&quot;</span>);</span><br><span class="line">         <span class="comment">// 加载配置文件,构造SqlSessionFactory</span></span><br><span class="line">        SqlSessionFactory sqlSessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(inputStream );</span><br><span class="line">         <span class="comment">// 使用SqlSessionFactory构造一个SqlSession</span></span><br><span class="line">        SqlSession sqlSession = sqlSessionFactory .openSession();</span><br><span class="line">         <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 执行statement</span></span><br><span class="line"><span class="comment">         * 参数1：statement的id 建议使用 namespace.statementId</span></span><br><span class="line"><span class="comment">         * 参数2：输入参数的值,它的类型要和映射文件中的parameterType类型一致</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        User user = sqlSession .selectOne(<span class="string">&quot;com.sun.test.mapper.UserMapper.findById&quot;</span> , <span class="number">1</span>);</span><br><span class="line">         <span class="comment">// 输出结果</span></span><br><span class="line">        System. out .println(user );</span><br><span class="line">         <span class="comment">// 关闭SqlSession</span></span><br><span class="line">        sqlSession .close();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>Resources：MyBatis中的一个工具类,可以从classpath或其他位置加载资源文件。</li>
<li>SqlSessionFactoryBuilder： 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。因此 SqlSessionFactoryBuilder 实例的最佳范围是方法范围（也就是局部方法变量）。</li>
<li>SqlSessionFactory：一旦被创建就应该在应用的运行期间一直存在,所以它应该是单例的,且在应用运行期间不要多次创建。</li>
<li>SqlSession：用于操作数据库的对象,每个线程都应该有一个SqlSession实例,它是多例的,并且它是线程不安全的,不能放在全局变量上。</li>
</ul>
<h3 id="5-自增主键"><a href="#5-自增主键" class="headerlink" title="5.自增主键"></a>5.自增主键</h3><p>如果你的数据库支持自动生成主键的字段,那么你可以设置 useGeneratedKeys=”true”,再把keyProperty设置到目标属性上即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;insert id&#x3D;&quot;insertUser&quot; useGeneratedKeys&#x3D;&quot;true&quot; parameterType &#x3D;&quot;com.sun.test.entity.User&quot; keyProperty&#x3D;&quot;id&quot;&gt;</span><br><span class="line">     insert into user(username,birthday,sex,address)</span><br><span class="line">     values(#&#123;username&#125;,#&#123;birthday&#125;,#&#123;sex&#125;,#&#123;address&#125;)</span><br><span class="line">&lt;&#x2F;insert&gt;</span><br></pre></td></tr></table></figure>
<p>如果不支持自动生成主键则可以使用另外一种方法生成主键</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt; insert id&#x3D; &quot;insertUser&quot; parameterType &#x3D;&quot;com.sun.test.entity.User&quot; &gt;</span><br><span class="line">          &lt;!-- 返回自增主键</span><br><span class="line">             keyProperty:生成主键的属性</span><br><span class="line">             resultType:生成主键的类型</span><br><span class="line">             order:查询主键SQL的执行顺序,相对于insert,如果设置为 BEFORE，那么它会首先选择主键，设置 keyProperty 然后执行插入语句。</span><br><span class="line">             如果设置为 AFTER，那么会先执行插入语句。</span><br><span class="line">             LAST_INSERT_ID():MySQL的函数,获取最后插入的主键</span><br><span class="line">         --&gt;</span><br><span class="line">          &lt; selectKey keyProperty &#x3D;&quot;id&quot; resultType &#x3D;&quot;int&quot; order&#x3D; &quot;AFTER&quot;&gt;</span><br><span class="line">             select LAST_INSERT_ID()</span><br><span class="line">          &lt;&#x2F; selectKey&gt;</span><br><span class="line">         insert into user(username,birthday,sex,address)</span><br><span class="line">        values(#&#123;username&#125;,#&#123;birthday&#125;,#&#123;sex&#125;,#&#123;address&#125;)</span><br><span class="line">     &lt;&#x2F;insert &gt;</span><br></pre></td></tr></table></figure>
<h4 id="与-的区别"><a href="#与-的区别" class="headerlink" title="#{} 与 ${}的区别"></a>#{} 与 ${}的区别</h4><ol>
<li>#{}可以表示为占位符?,#{id}里面的id表示输入参数的参数名称,如果是简单类型,则名称可以任意填写。</li>
<li>${}表示字符串替换,${value},value表示输入参数的参数名称,如果是简单类型,则名称必须为value。</li>
<li>${}是不安全的,会导致潜在的sql注入攻击,但如果要动态传入order by的列名则必须使用${} 即：order by ${columnName}。</li>
</ol>
<h3 id="6-使用Mapper构建Dao"><a href="#6-使用Mapper构建Dao" class="headerlink" title="6.使用Mapper构建Dao"></a>6.使用Mapper构建Dao</h3><p>使用Mapper构建Dao则只需要开发接口即可。</p>
<h4 id="规范"><a href="#规范" class="headerlink" title="规范"></a>规范</h4><ol>
<li>mapper接口的全限定名称要和mapper映射文件的namespace一致。</li>
<li>mapper接口的方法名称要和mapper映射文件的MappedStatement的id一致。</li>
<li>mapper接口的方法参数类型与返回值类型要和mapper映射文件的MappedStatement的parameterType与resultType一致。</li>
</ol>
<p>例:</p>
<p><img src="http://i4.buimg.com/fb28faf508066198.png" alt="mapper"></p>
<p><img src="http://i4.buimg.com/0382b4a78a6080a2.png" alt="mapper.xml"></p>
<p><img src="http://i4.buimg.com/134368652f63916c.png" alt="test"></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/Java/" rel="tag"># Java</a>
              <a href="/yuwanzi.io/tags/MyBatis/" rel="tag"># MyBatis</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/06/11/2016-06-11-MyBatis-XML%E9%85%8D%E7%BD%AE%E4%B8%8E%E6%98%A0%E5%B0%84%E6%96%87%E4%BB%B6/" rel="next" title="MyBatis-XML配置与映射文件">
                  MyBatis-XML配置与映射文件 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
